package com.jzl.canal_consumer.mycat.aop;


import com.jzl.canal_consumer.mycat.MycatAnnotation;
import com.jzl.util.LoggerUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * @author ZhenWuWang
 */
@Aspect
@Component
public class JdbcTemplateInterceptor
{
    @Value("${mycat.schema:false}")
    private boolean mycatSchema;

    @Around("execution(public * org.springframework.jdbc.core.JdbcTemplate.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable
    {
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();

        // 获取参数名
        String[] parameterNames = codeSignature.getParameterNames();
        if (parameterNames == null || parameterNames.length == 0)
        {
            return joinPoint.proceed();
        }

        //目前只修改参数含有sql语句的方法
        int index = 0;
        for (; index < parameterNames.length; index++)
        {
            if ("sql".equals(parameterNames[index]))
            {
                break;
            } else if (index == parameterNames.length - 1)
            {
                return joinPoint.proceed();
            }
        }

        //获取参数对象数组
        Object[] params = joinPoint.getArgs();
        String sql = (String) params[index];
        int indexOf = sql.indexOf('.');
        if (indexOf > 0)
        {
            String[] strings = sql.split("\\.");
            indexOf = strings[0].indexOf('`');
            if (indexOf > 0)
            {
                strings[0] = strings[0].substring(0, indexOf - 1).concat(" ");
            }

            StringBuilder sb1 = new StringBuilder();

            for (String string : strings)
            {
                sql = sb1.append(string).toString();
            }

        }
        params[0] = mycatSchema ? MycatAnnotation.appendSchemaAnnotation(sql) : sql;
        LoggerUtil.info("finally sql:" + params[0]);
        return joinPoint.proceed(params);
    }
}
